package com.design.strategy;


import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 策略模式bean监听器
 *
 * @author Zee
 * @date 2021年8月27日
 */
@Component
public class StrategyListener implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        Map<String, Object> beans = event.getApplicationContext().getBeansWithAnnotation(Strategy.class);
        StrategyContext strategyContext = event.getApplicationContext().getBean(StrategyContext.class);
        beans.forEach((name, bean) -> {
            Strategy strategy = bean.getClass().getAnnotation(Strategy.class);
            strategyContext.setStrategyService(strategy.value().code, (StrategyService) bean);
        });
    }
}
